package com.mazong.servershirobb.config;

import com.mazong.servershirobb.mapper.IDbSecurityMapper;
import com.mazong.servershirobb.pojo.TbUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Slf4j
public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    IDbSecurityMapper iDbSecurityMapper;

    //--用户验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("doGetAuthenticationInfo,执行用户验证");

        //--获取用户输入的密码
        UsernamePasswordToken userinfo = (UsernamePasswordToken)token;
        log.info("user={}", userinfo.getUsername());

        //--从数据库获取用户的密码
        TbUser user = iDbSecurityMapper.getUserByName(userinfo.getUsername());
        if(user == null) {
            log.info("doGetAuthenticationInfo,用户不存在");
            return null;
        }

        //--验证用户密码
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }

    //--权限校验
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("doGetAuthenticationInfo,执行用户权限");

        //--1 获得用户信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();

        //--2 获取权限
        List<String> perms = iDbSecurityMapper.getPermissionsById(user.getId());
        if(perms == null) {
            log.info("{} 没有任何权限！", user.getUsername());
            return null;
        }

        //--3
        info.addStringPermissions(perms);

        return info;
    }
}
